package multiThread;

/* Inter Thread Communication
 */

class Work {
	int i;
	boolean flag = false;

	synchronized int get() {
		if (flag == false) {
			try {
				wait();
				Thread.sleep(500);
			} catch (Exception e) {
			}
		}
		flag = false;
		notifyAll();
		return i;
	}

	synchronized void put(int i) {
		if (flag == true) {
			try {
				wait();
				Thread.sleep(500);
			} catch (Exception e) {
			}
		}
		System.out.println("Put value: " + i);
		this.i = i;
		flag = true;
		notifyAll();
	}
}

class Put implements Runnable {
	int i = 0;
	Work w;

	public Put(Work w) {
		this.w = w;
		Thread t = new Thread(this);
		t.start();
	}

	public void run() {
		while (true)
			w.put(i++);
	}

}

class Get implements Runnable {
	Work w;

	public Get(Work w) {
		this.w = w;
		Thread t = new Thread(this);
		t.start();
	}

	public void run() {
		while (true)
			System.out.println("Get value: " + w.get());
	}
}

public class MyThread11 {
	@SuppressWarnings("unused")
	public static void main(String args[]) {
		Work w = new Work();
		Get g = new Get(w);
		Put p = new Put(w);
	}
}
